<template>
  <div>
    <!-- 查询栏 -->
    <div class="toolbar">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            style="width: 100%" />
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            style="width: 100%" />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入姓名或小区名称"
            clearable
            style="width: 100%" />
        </el-col>
        <el-col :span="3">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
            style="width: 100%">
            查询
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-button
            @click="resetSearch"
            style="width: 100%">
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 按钮栏 -->
    <div class="button-bar">
      <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">添加</el-button>
    </div>

    <!-- 表格展示 -->
    <el-table
      :data="paginatedData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="业主ID" width="90" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="idCard" label="身份证号" width="180" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="memberType" label="成员类型" width="100" />
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="birth" label="出生日期" width="120" />
      <el-table-column prop="occupation" label="职业" width="120" />
      <el-table-column label="成员照片" width="100">
        <template #default="scope">
          <img
            :src="scope.row.photo"
            alt="头像"
            style="width: 60px; height: 60px; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column prop="house" label="所属房产" width="120" />
      <el-table-column prop="community" label="所属小区" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="remark" label="备注" width="150" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <i class="el-icon-edit" @click="openEditDialog(scope.row)" style="cursor:pointer; margin-right:10px" />
          <i class="el-icon-delete" @click="confirmDelete(scope.row)" style="cursor:pointer" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="total, prev, pager, next, jumper"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="filteredData.length"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: center;" />

    <!-- 删除确认弹窗 -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="30%">
      <p>确定要删除该成员记录吗？</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteConfirmed">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑人员弹窗 -->
    <el-dialog
      :title="editForm.id ? '编辑人员' : '添加人员'"
      :visible.sync="editDialogVisible"
      width="600px">
      <el-form :model="editForm" label-width="100px" :rules="rules" ref="editFormRef" label-position="left">
        <el-form-item label="业主ID" prop="id">
          <el-input v-model="editForm.id" :disabled="!!editForm.id" />
        </el-form-item>
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="editForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard" required>
          <el-input v-model="editForm.idCard" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" required>
          <el-input v-model="editForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="成员类型" prop="memberType" required>
          <el-select v-model="editForm.memberType" placeholder="请选择成员类型">
            <el-option label="户主" value="户主" />
            <el-option label="家属" value="家属" />
            <el-option label="租户" value="租户" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender" required>
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth" required>
          <el-date-picker
            v-model="editForm.birth"
            type="date"
            placeholder="选择出生日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="editForm.occupation" autocomplete="off" />
        </el-form-item>
        <el-form-item label="成员照片" prop="photo">
          <el-input v-model="editForm.photo" placeholder="请输入照片URL" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属房产" prop="house" required>
          <el-input v-model="editForm.house" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属小区" prop="community" required>
          <el-input v-model="editForm.community" autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="editForm.remark" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      startDate: '',
      endDate: '',
      currentPage: 1,
      pageSize: 5,
      selection: [],
      deleteDialogVisible: false,
      deleteTarget: null,
      editDialogVisible: false,
      editForm: {
        id: null,
        name: '',
        idCard: '',
        phone: '',
        memberType: '',
        gender: '',
        birth: '',
        occupation: '',
        photo: '',
        house: '',
        community: '',
        createTime: '',
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        memberType: [{ required: true, message: '请选择成员类型', trigger: 'change' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        birth: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
        house: [{ required: true, message: '请输入所属房产', trigger: 'blur' }],
        community: [{ required: true, message: '请输入所属小区', trigger: 'blur' }]
      },
      tableData: [
        {
          id: 1,
          name: '张三',
          idCard: '330102199012123456',
          phone: '13800000001',
          memberType: '户主',
          gender: '男',
          birth: '1990-12-12',
          occupation: '工程师',
          photo: 'https://via.placeholder.com/60',
          house: '1栋102室',
          community: '金华万府',
          createTime: '2024-06-01 10:00:00',
          remark: '无',
        },
        {
          id: 2,
          name: '李四',
          idCard: '330102198805203456',
          phone: '13788888888',
          memberType: '家属',
          gender: '女',
          birth: '1988-05-20',
          occupation: '教师',
          photo: 'https://via.placeholder.com/60',
          house: '2栋301室',
          community: '星河时代',
          createTime: '2024-06-10 14:20:00',
          remark: '长期居住',
        },
      ],
    };
  },
  computed: {
    filteredData() {
      return this.tableData.filter(item => {
        const keywordMatch =
          !this.searchKeyword ||
          item.name.includes(this.searchKeyword) ||
          item.community.includes(this.searchKeyword);
        const startMatch =
          !this.startDate || new Date(item.createTime) >= new Date(this.startDate);
        const endMatch =
          !this.endDate || new Date(item.createTime) <= new Date(this.endDate);
        return keywordMatch && startMatch && endMatch;
      });
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.filteredData.slice(start, start + this.pageSize);
    },
  },
  methods: {
    handleSearch() {
      this.currentPage = 1;
    },
    resetSearch() {
      this.searchKeyword = '';
      this.startDate = '';
      this.endDate = '';
      this.currentPage = 1;
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleSelectionChange(val) {
      this.selection = val;
    },
    handleBatchDelete() {
      if (!this.selection.length) {
        this.$message.warning('请选择要删除的记录');
        return;
      }
      this.$confirm('确定批量删除选中的人员吗？', '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const ids = this.selection.map(item => item.id);
        this.tableData = this.tableData.filter(item => !ids.includes(item.id));
        this.selection = [];
        this.$message.success('批量删除成功');
      });
    },
    confirmDelete(row) {
      this.deleteTarget = row;
      this.deleteDialogVisible = true;
    },
    deleteConfirmed() {
      if (this.deleteTarget) {
        this.tableData = this.tableData.filter(item => item.id !== this.deleteTarget.id);
        this.$message.success('删除成功');
        this.deleteDialogVisible = false;
      }
    },
    openAddDialog() {
      this.resetEditForm();
      this.editDialogVisible = true;
    },
    openEditDialog(row) {
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    resetEditForm() {
      this.editForm = {
        id: null,
        name: '',
        idCard: '',
        phone: '',
        memberType: '',
        gender: '',
        birth: '',
        occupation: '',
        photo: '',
        house: '',
        community: '',
        createTime: '',
        remark: ''
      };
    },
    saveEdit() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return;

        if (this.editForm.id) {
          // 编辑：更新对应项
          const index = this.tableData.findIndex(item => item.id === this.editForm.id);
          if (index !== -1) {
            this.$set(this.tableData, index, { ...this.editForm });
          }
          this.$message.success('编辑成功');
        } else {
          // 添加：生成新id并插入
          const maxId = this.tableData.reduce((max, item) => (item.id > max ? item.id : max), 0);
          this.editForm.id = maxId + 1;
          this.editForm.createTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
          this.tableData.push({ ...this.editForm });
          this.$message.success('添加成功');
        }
        this.editDialogVisible = false;
      });
    }
  }
};
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
}
.button-bar {
  background: #f2f2f2;
  padding: 6px 10px;
  margin-bottom: 20px;
}
.el-button {
  margin-right: 10px;
}
.el-icon-edit,
.el-icon-delete {
  cursor: pointer;
  margin-right: 10px;
  color: #2a6496;
}
</style>
